package com.wxj.bank.storage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wxj.bank.module.constant.Constants;
import com.wxj.bank.module.page.PageBean;
import com.wxj.bank.module.utils.UUIDUtils;
import com.wxj.bank.storage.dao.CategoryMapper;
import com.wxj.bank.storage.model.Category;
import com.wxj.bank.storage.model.CategoryExample;
import com.wxj.bank.storage.service.ICategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author shengtao
 * @Description: 商品分类
 * @date 2019/02/19 15:52
 */
@Service
public class CategoryServiceImpl implements ICategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category save(Category category) {
        category.setId(UUIDUtils.genUUID());
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public void save(List<Category> categories) {
        categories.stream().map(category -> {category.setId(UUIDUtils.genUUID());return category;}).collect(toList());
        categoryMapper.batchInsert(categories);
    }

    @Override
    public void remove(String id) {
        categoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Category update(Category category) {
        categoryMapper.updateByPrimaryKey(category);
        return category;
    }

    @Override
    public Category find(String id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Category> find(Category category) {
        CategoryExample example = new CategoryExample();
        CategoryExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(category.getId())){
            criteria.andIdEqualTo(category.getId());
        }
        if(StringUtils.isNotBlank(category.getName())){
            criteria.andNameLike(category.getName()+ Constants.SYMBOL_PERCENT);
        }
        return categoryMapper.selectByExample(example);
    }

    @Override
    public PageBean<Category> find(Category category, PageBean<Category> page) {
        CategoryExample example = new CategoryExample();
        CategoryExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(category.getId())){
            criteria.andIdEqualTo(category.getId());
        }
        if(StringUtils.isNotBlank(category.getName())){
            criteria.andNameLike(category.getName()+ Constants.SYMBOL_PERCENT);
        }
        Page<Category> pages = PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        categoryMapper.selectByExample(example);
        return new PageBean<>(pages);
    }
}
